/**
 * Created by weidong on 14-2-15.
 */
//sta首次上线认证第一个交互接口
var express = require('express');
var app = express();
var log = require("../lib/log");
var cfg = require('../config');
var url = require('url');
var db = require('../lib/db.js');
var RUtil = require('./dataformatUtil');
var crypto = require('crypto');
//var async = require('async');

var virapinfo = require('../models/virapinfo');
var customerinfo = require('../models/customerinfo');
function adwifi(request,response)
{
    if(RUtil.checkVaildForURL(request)!==0) return;


    if(request.method.toUpperCase() === "GET")
    {
        if(typeof(request.query.action)!=="undefined" && request.query.action =="topage")
        {
            console.log("5.[request]AP重定向STA访问topage："+url.parse(request.url).query);
            var sessionid=request.query.sessionid;
            var gwip=request.query.gwip;
            var data={msg:'可以上网啦',onlinemsg:'我要走了下线',type:'online',nexttype:'offline',sessionid:sessionid,gwip:gwip};

            //判断该ap的商户是否要认证成功后跳转到商户的网站
            virapinfo.selectAPWiFiWithAPMac(request.query.apmac, function(error,results) {
                if((error)!== null)
                {
                    // 数据库异常
                    response.render("useronlineinfo.html",data);
                }
                else if(results.length <= 0) {
                    //没有
                    response.render("useronlineinfo.html",data);
                } else {
                    function sleep(ms) {
                        var startTime = new Date().getTime();
                        while(new Date().getTime()<startTime+ms);
                    }

                    //sleep(3000);

                    console.log("topage:"+results[0].wifiredirecturl);
                    if(results[0].wifiredirecturl!=="useronlineinfo.html")
                    {
                        response.redirect(results[0].wifiredirecturl);
                    }
                    else
                        response.render("useronlineinfo.html",data);
                }
            });

        }
        else if(request.query.action=="offline") {
            console.log("AP响应用户下线");
            var sessionid=request.query.sessionid;
            var gwip=request.query.gwip;
            var data={msg:'您已经下线',onlinemsg:'我要继续上网',type:'offline',nexttype:'online',sessionid:sessionid,gwip:gwip};
            response.render("useronlineinfo.html",data);
        }
        else if(typeof(request.query.action)!=="undefined" && request.query.action =="passthrough")
        {
            console.log("url passthrough："+url.parse(request.url).query);


            var whereclause={apmac:request.quer.apmac,usermac:request.quer.wlanusermac};
            virapinfo.selectForPassthrough(whereclause, function(error,results) {
                if((error)!== null)
                {
                    // 数据库异常
                    retFlag=1;
                    reason="system fault:errno("+error.errno+")";
                } else if(results.length <= 0) {
                    // 不存在，直接响应页面
                    retFlag=1;
                    reason="the customer did not access network in the same group.";
                } else {
                    //存在数据
                    retFlag=0;
                }
                var redirecturl="http://"+request.session.gwip
                    +"/?sessionid="+crypto.createHash('md5').update(request.session.allquerystr).digest('hex')
                    +"_"+results.insertId
                    +"&retflag="+retFlag
                    +"&"+request.session.allquerystr;
                console.log("passthrough 响应消息:"+redirecturl);
                response.redirect(redirecturl);
            });

        }
        else
        {
            console.log("1.[request]AP重定向STA访问到adwifi："+url.parse(request.url).query);
            request.session.allquerystr=url.parse(request.url).query;
            request.session.wlanuserfirsturl=request.query.wlanuserfirsturl;
            request.session.gwip=request.query.gwip;


            var apuserid=-1;
            var apwifiid=-1;
            var customerid=-1;


            //根据apmac查找到userid，同时查找customer表，如果上线的用户不存在则插入customer，并将customerid传入广告页面
            virapinfo.selectMac(request.query.apmac, function(error,results) {
                if((error)!== null)
                {
                    // 数据库异常
                    response.redirect("404.html");
                } else if(results.length <= 0) {
                    // 不存在
                    response.redirect("404.html");
                } else {
                    //存在数据
                    apuserid=results[0].userid;
                    apwifiid=results[0].wifiid;

                    //这里应该根据apmac+usermac一起查找
                    var whereclause={apmac:request.query.apmac,wlanusermac:request.query.wlanusermac};
                    customerinfo.selectCustExists(whereclause, function(error,results) {
                        var adurl="";
                        if((error)!== null)
                        {
                            // 数据库异常
                            reason="system fault:errno("+error.errno+")";
                            response.redirect("404.html");
                        }
                        else if(results.length <= 0)
                        {
                            // 不存在，插入一条记录并重定向到广告
                            var data = RUtil.customerinfo(request);
                            data.wifiid=apwifiid;
                            data.userid=apuserid;
                            data.custphone='';
                            data.custname='';
                            data.custregdatetime= new Date();
                            data.custmac=request.query.wlanusermac;
                            data.custip=request.query.wlanuserip;
                            data.apmac=request.query.apmac;
                            customerinfo.insert(data, function(error,results) {
                                if((error)!== null)
                                {
                                    // 数据库异常
                                    response.redirect("404.html");
                                }
                                else if(results.length <= 0) {
                                    //没有
                                    response.redirect("404.html");
                                } else {
                                    if(typeof(request.session.wlanuserfirsturl)!=="undefined" && request.session.wlanuserfirsturl.indexOf("autologin")!==-1)
                                    {
                                        var redirecturl="http://"+request.session.gwip
                                            +"/?sessionid="+crypto.createHash('md5').update(request.session.allquerystr).digest('hex')
                                            +"_"+results.insertId
                                            +"&retflag=0"
                                            +"&"+request.session.allquerystr;
                                        console.log("autologin:"+redirecturl);
                                        response.redirect(redirecturl);
                                    }
                                    else
                                    {

                                        adurl="/adshow.html?userid="+apuserid+"&customerid="+results.insertId;
                                        console.log("directlogin:"+adurl);
                                        log.info("1.[request]adwifi直接重定向到广告（可不需其他步骤）："+adurl);
                                        response.redirect(adurl);
                                    }
                                }
                            });

                        }
                        else {
                            //存在数据
                            //更新状态为在线flag=1
                            customerinfo.updateOnline(whereclause, function(error,results) {});
                            if(typeof(request.session.wlanuserfirsturl)!=="undefined" && request.session.wlanuserfirsturl.indexOf("autologin")!==-1)
                            {
                                var sessid;

                                if(typeof(request.session.allquerystr)!=="undefined" && request.session.allquerystr!=="")
                                {sessid=request.session.allquerystr; }
                                else
                                {sessid=Math.floor(Math.random()*(100000))+"";}
                                var redirecturl="http://"+request.session.gwip
                                    +"/?sessionid="+crypto.createHash('md5').update(sessid).digest('hex')
                                    +"_"+results[0].customerid
                                    +"&retflag=0"
                                    +"&autologin=1"
                                    +"&"+request.session.allquerystr;
                                console.log("autologin:"+redirecturl);
                                response.redirect(redirecturl);
                            }
                            else
                            {
                                //apuserid=results[0].userid;
                                customerid=results[0].customerid;
                                adurl="/adshow.html?userid="+apuserid+"&customerid="+customerid;
                                console.log("directlogin:"+adurl);
                                log.info("1.[request]adwifi直接重定向到广告（可不需其他步骤）："+adurl);
                                response.redirect(adurl);
                            }
                        }

                    });
                }
            });
        }
    }


    else
    {
        if(request.method.toUpperCase() === "POST" && request.body.action=="useroffline") {
            console.log("用户主动下线");
            var redurl="http://"+request.body.gwip+"/?action=offline&sessionid="+request.body.sessionid;
            console.log("发送重定向到AP："+redurl);
            response.redirect(redurl);

        }
        else if(request.method.toUpperCase() === "POST" && request.body.action=="useronline") {
            console.log("用户再次上线");
            response.redirect("http://www.baidu.com?relogin");
        }
    }


}
exports.adwifi = adwifi;
